<?php

namespace Forwzb\Yii2Api\api;

use yii\base\Model;

/**
 * API 响应格式Trait
 * ```
 * //xxx.controller.php
 * use ApiFormatterTrait;
 * $this->api()->success('',null,0);
 * $this->api()->error('',null,0);
 * $this->api()->modelError($model);
 * ```
 */
trait ApiFormatterTrait
{
    public function api(): ApiFormatter
    {
        return new ApiFormatter();
    }

    public function modelError(Model $model): ApiFormatter
    {
        $errors = $model->getErrorSummary(true);
        $message = empty($errors) ? \Yii::t('app', 'Failed to load form data.') : $errors[0];
        return $this->api()
            ->error($message, ['errors' => $model->getErrors()]);
    }
}